
"use client";

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { Layout, Typography, List, Card, Input, Button, Space } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useParams } from 'next/navigation';
import api from '../../../utils/api'; // 假设 api 模块路径是这样，需根据实际情况调整
import { useUser } from "../../../context/userContext"; // 假设 userContext 路径是这样，需根据实际情况调整


const { Content } = Layout;
const { Title, Text } = Typography;


// 辅助函数：对文本中出现的关键字进行标记处理
function highlightText(text, keyword) {
  if (!keyword) return <>{text}</>;
  const regex = new RegExp(`(${keyword})`, 'gi');
  const parts = text.split(regex);
  return (
    <>
      {parts.map((part, index) => {
        const isMatch = part.toLowerCase() === keyword.toLowerCase();
        return isMatch ? (
          <mark key={index} style={{ backgroundColor: '#ffc069', padding: '0 2px' }}>
            {part}
          </mark>
        ) : (
          <span key={index}>{part}</span>
        );
      })}
    </>
  );
}

const listItemStyle = {
  border: '1px solid #e8e8e8',
  borderRadius: 8,
  padding: 16,
  marginBottom: 16,
  transition: 'box-shadow 0.3s',
  cursor: 'pointer',
  ':hover': {
    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)'
  }
};

export default function SearchPage({ params }) {
  const [keyword, setKeyword] = useState(decodeURIComponent(params.keyword));
  const [searchResults, setSearchResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const { user } = useUser();

  useEffect(() => {
    if (keyword.trim()!== '') {
      fetchSearchResults();
    }
  }, [keyword]);

  const fetchSearchResults = async () => {
    setLoading(true);
    try {
      const url = '/posts/search';
      const params = {
        keyword: keyword.trim(),
        page: '1',
        pageSize: '10'
      };
      const headers = {
        'Authorization': `Bearer ${user.access_token}`,
        'Content-Type': 'application/json'
      };
      const response = await api.get(url, { params, headers });
      if (response.status === 200) {
        const searchData = Array.isArray(response.data) ? response.data : [];
        const searchWithDisplayName = await Promise.all(
          searchData.map(async (post) => ({
            ...post,
            authorDisplayName: await fetchAuthorDisplayName(post.authorId)
          }))
        );
        setSearchResults(searchWithDisplayName);
      }
    } catch (error) {
      console.error('搜索数据获取失败:', error);
      setSearchResults([]);
    } finally {
      setLoading(false);
    }
  };

  const fetchAuthorDisplayName = async (authorId) => {
    try {
      const userResponse = await api.get('/users/info', {
        params: { id: authorId }
      });
      return userResponse.data?.display_name || '未知作者';
    } catch (error) {
      console.error(`获取作者 ${authorId} 信息失败:`, error);
      return '未知作者';
    }
  };

  const handleSearch = (newKeyword) => {
    setKeyword(newKeyword);
  };

  const dataToRender = keyword.trim()!== ''? searchResults : mockPosts;

  return (
    <Content style={{ padding: '20px' }}>
      <div style={{ marginBottom: '20px', display: 'flex', alignItems: 'center' }}>
        <Input
          placeholder="输入关键词搜索帖子"
          prefix={<SearchOutlined />}
          value={keyword}
          onChange={(e) => handleSearch(e.target.value)}
          style={{ width: 'calc(100% - 80px)', marginRight: '10px' }}
        />
        <Button type="primary" onClick={() => handleSearch(keyword)}>
          搜索
        </Button>
      </div>
      <div style={{ marginBottom: '10px', fontSize: '14px', color: '#555' }}>
        下面为你展示“{keyword}”相关帖子
      </div>
      <List
        itemLayout="horizontal"
        dataSource={dataToRender}
        locale={{ emptyText: "没有相关帖子" }}
        renderItem={(item) => (
          <div style={listItemStyle}>
            <Link href={`/posts/${item.postId || item.id}`} passHref prefetch>
              <div>
                <Title level={4} style={{ margin: 0 }}>
                  {highlightText(item.title, keyword)}
                </Title>
                <Text type="secondary" style={{ marginTop: 4, display: 'block' }}>
                  作者：{item.author || item.authorDisplayName}
                </Text>
                <Text style={{ marginTop: 8, display: 'block', color: '#666' }}>
                  {highlightText(item.content, keyword)}
                </Text>
                <Text type="secondary" style={{ marginTop: 8, display: 'block', fontSize: 12, color: '#999' }}>
                  {item.createdAt}
                </Text>
              </div>
            </Link>
            <Space style={{ marginTop: 8 }}>
              <Button type="text" style={{ color: '#666' }}>
                <span style={{ display: 'flex', alignItems: 'center' }}>
                  <span>{item.likes}</span>
                  <span style={{ marginLeft: 5 }}>👍</span>
                </span>
              </Button>
              <Button type="text" style={{ color: '#666' }}>
                <span style={{ display: 'flex', alignItems: 'center' }}>
                  <span>{item.views || 0}</span>
                  <span style={{ marginLeft: 5 }}>👀</span>
                </span>
              </Button>
              <Button type="text" style={{ color: '#666' }}>
                <span style={{ display: 'flex', alignItems: 'center' }}>
                  <span>{item.favorites || item.favourites || 0}</span>
                  <span style={{ marginLeft: 5 }}>⭐</span>
                </span>
              </Button>
            </Space>
          </div>
        )}
      />
      {loading && <div>加载中...</div>}
    </Content>
  );
}    